<?php
namespace app\modules\app\models;

use yii\db\ActiveRecord;

class ExerciseTime extends ActiveRecord
{

    public static function tableName()
    {
        return '{{%exercise_time}}';
    }

    //一周以来每天的做题正确百分比
    public static function getTime($time='')
    {
        $uid = \Yii::$app->session->get('uid');

        if ($time == false) {
            $date = date('w');//星期几
            if ($date > 1) {
                $startTime = strtotime('last monday');//星期1
            } elseif ($date = 1) {
                $startTime = strtotime(date('Y-m-d'), time());
            } else {
                $startTime = strtotime('next week monday');//星期1
            }
        } else {
            $startTime = $time;
        }
        $data=array();
        static $n=0;
        static $count=0;
        for($i=0;$i<7;$i++){
            $start=$startTime+$i*24*3600;
            $end=$startTime+($i+1)*24*3600;
            $time=ExerciseTime::find()->asArray()->where('uid='.$uid.' and createtime>'.$start.' and  createtime<'.$end)->one();
            $data[$i]['listen']=$time==false?0:$time['listen'];
            $data[$i]['spoken']=$time==false?0:$time['spoken'];
            $data[$i]['read']=$time==false?0:$time['read'];
            $data[$i]['write']=$time==false?0:$time['write'];
            if($data[$i]['listen']!=0||$data[$i]['spoken']!=0||$data[$i]['read']!=0||$data[$i]['write']!=0){
                $n++;
                $count+=$data[$i]['listen']+$data[$i]['spoken']+$data[$i]['read']+$data[$i]['write'];
            }
            $data['avgTime']=$n!=false?round(($count/$n)):0;
        }
        return $data;
    }
    //一周以来每天的做题正确百分比
    public static function getAllTime()
    {
        $uid = \Yii::$app->session->get('uid');
        $time = ExerciseTime::find()->select('SUM(`listen`) as listenSum,SUM(`read`) as readSum,SUM(`spoken`) as spokenSum,SUM(`write`) as writeSum')->asArray()->where('uid=' . $uid)->one();
        return $time;
    }
}
